<template>
  <div class="coupon-list">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="优惠券类型">
          <el-select v-model="searchForm.type" placeholder="请选择优惠券类型" style="width: 200px;">
            <el-option label="全部" :value="0"></el-option>
            <el-option label="每满减" :value="1"></el-option>
            <el-option label="折扣" :value="2"></el-option>
            <el-option label="无门槛" :value="3"></el-option>
            <el-option label="满减" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券状态">
          <el-select v-model="searchForm.status" placeholder="请选择优惠券状态" style="width: 200px;">
            <el-option label="全部" :value="0"></el-option>
            <el-option label="待发放" :value="1"></el-option>
            <el-option label="未开始" :value="2"></el-option>
            <el-option label="进行中" :value="3"></el-option>
            <el-option label="已结束" :value="4"></el-option>
            <el-option label="暂停" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券名称">
          <el-input v-model="searchForm.name" placeholder="请输入优惠券名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区域 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>优惠券列表</span>
          <el-button type="primary" @click="handleAdd">新增优惠券</el-button>
        </div>
      </template>

      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="200"></el-table-column>
        <el-table-column prop="name" label="优惠券名称"></el-table-column>
        <el-table-column prop="discountType" label="优惠券类型" width="100">
          <template #default="scope">
            {{ getDiscountTypeName(scope.row.discountType) }}
          </template>
        </el-table-column>
        <el-table-column prop="thresholdAmount" label="门槛金额" width="100"></el-table-column>
        <el-table-column prop="discountValue" label="优惠金额/折扣" width="150"></el-table-column>
        <el-table-column prop="obtainWay" label="领取方式" width="100">
          <template #default="scope">
            {{ getObtainWayName(scope.row.obtainWay) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalNum" label="总发放数" width="100"></el-table-column>
        <el-table-column prop="userLimit" label="每人限领" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="small" @click="handleViewCodes(scope.row)" v-if="scope.row.obtainWay === 2">查看兑换码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination v-model:current-page="pagination.pageNo" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
      </div>
    </el-card>

    <!-- 编辑优惠券弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑优惠券" width="600px" @close="handleDialogClose">
      <el-form 
        :model="editCouponForm" 
        :rules="editRules" 
        ref="editFormRef" 
        label-width="120px"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="editCouponForm.name" placeholder="请输入优惠券名称"></el-input>
        </el-form-item>

        <el-form-item label="使用范围" prop="specific">
          <el-radio-group v-model="editCouponForm.specific">
            <el-radio :label="false">全部课程分类</el-radio>
            <el-radio :label="true">指定课程分类</el-radio>
          </el-radio-group>
          <el-select v-model="editCouponForm.scopes" placeholder="请选择课程分类" multiple v-if="editCouponForm.specific">
            <!-- 这里需要动态加载课程分类 -->
          </el-select>
        </el-form-item>

        <el-form-item label="优惠券类型" prop="discountType">
          <el-radio-group v-model="editCouponForm.discountType">
            <el-radio :label="1">每满减</el-radio>
            <el-radio :label="2">折扣</el-radio>
            <el-radio :label="3">无门槛</el-radio>
            <el-radio :label="4">满减</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="门槛金额" prop="thresholdAmount" v-if="editCouponForm.discountType !== 3">
          <el-input-number v-model="editCouponForm.thresholdAmount" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="优惠金额/折扣" prop="discountValue">
          <el-input-number v-model="editCouponForm.discountValue" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="最大优惠金额" prop="maxDiscountAmount" v-if="editCouponForm.discountType === 1 || editCouponForm.discountType === 4">
          <el-input-number v-model="editCouponForm.maxDiscountAmount" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="推广方式" prop="obtainWay">
          <el-radio-group v-model="editCouponForm.obtainWay">
            <el-radio :label="1">手动领取</el-radio>
            <el-radio :label="2">指定发放</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="发放数量" prop="totalNum">
          <el-input-number v-model="editCouponForm.totalNum" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="每人限领" prop="userLimit">
          <el-input-number v-model="editCouponForm.userLimit" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :loading="editLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import couponApi from '@/api/coupon'
import { type CouponListResponseType, type CouponQueryType, type CouponFormDTO } from '@/api/coupon'

// 搜索表单
const searchForm = ref({
  type: 0,
  status: 0,
  name: ''
})

// 分页参数
const pagination = ref({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref<CouponListResponseType[]>([])
const loading = ref(false)

// 路由
const router = useRouter()

// 编辑弹窗相关
const editDialogVisible = ref(false)
const editFormRef = ref()
const editLoading = ref(false)
const currentEditId = ref(0)

// 编辑表单数据
const editCouponForm = ref<CouponFormDTO>({
  id: '',
  name: '',
  discountType: 1,
  thresholdAmount: 0,
  discountValue: 0,
  maxDiscountAmount: 0,
  obtainWay: 1,
  totalNum: 0,
  userLimit: 0,
  specific: false,
  scopes: []
})

// 编辑表单验证规则
const editRules = {
  name: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' }
  ],
  discountType: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  thresholdAmount: [
    { required: true, message: '请输入门槛金额', trigger: 'blur' }
  ],
  discountValue: [
    { required: true, message: '请输入优惠金额/折扣', trigger: 'blur' }
  ],
  totalNum: [
    { required: true, message: '请输入发放数量', trigger: 'blur' }
  ],
  userLimit: [
    { required: true, message: '请输入每人限领数量', trigger: 'blur' }
  ]
}

// 获取优惠券列表
const getCouponList = async () => {
  loading.value = true
  const couponQuery: CouponQueryType = {
    pageNo: pagination.value.pageNo,
    pageSize: pagination.value.pageSize,
    sortBy: 'id',
    isAsc: false,
    discountType: searchForm.value.type,
    status: searchForm.value.status,
    name: searchForm.value.name
  }
  try {
    const res: any = await couponApi.queryCouponByPage(couponQuery)
    tableData.value = res.data.data.list
    pagination.value.total = res.data.data.total
  } catch (error) {
    ElMessage.error('获取优惠券列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索优惠券
const handleSearch = () => {
  pagination.value.pageNo = 1
  getCouponList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    type: 0,
    status: 0,
    name: ''
  }
  pagination.value.pageNo = 1
  getCouponList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  pagination.value.pageNo = 1
  getCouponList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.value.pageNo = val
  getCouponList()
}

// 新增优惠券
const handleAdd = () => {
  router.push('/coupon/add')
}

// 编辑优惠券
const handleEdit = async (row: CouponListResponseType) => {
  try {
    // 获取优惠券详情
    const res: any = await couponApi.getCouponDetail(row.id)
    const detail = res.data.data
    
    // 填充表单数据
    editCouponForm.value = {
      id: detail.id,
      name: detail.name,
      discountType: detail.discountType,
      thresholdAmount: detail.thresholdAmount,
      discountValue: detail.discountValue,
      maxDiscountAmount: detail.maxDiscountAmount,
      obtainWay: detail.obtainWay,
      totalNum: detail.totalNum,
      userLimit: detail.userLimit,
      specific: detail.specific || false,
      scopes: detail.scopes || []
    }
    
    currentEditId.value = detail.id
    editDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取优惠券详情失败')
  }
}

// 提交编辑表单
const submitEditForm = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      editLoading.value = true
      try {
        const res: any = await couponApi.updateCoupon(editCouponForm.value)
        
        if (res.data.code === 200) {
          ElMessage.success('更新优惠券成功')
          editDialogVisible.value = false
          getCouponList()
        } else {
          ElMessage.error(`更新优惠券失败: ${res.data.msg}`)
        }
      } catch (error) {
        ElMessage.error('更新优惠券失败')
      } finally {
        editLoading.value = false
      }
    }
  })
}

// 关闭弹窗时的处理
const handleDialogClose = () => {
  editFormRef.value.resetFields()
}

// 删除优惠券
const handleDelete = (row: CouponListResponseType) => {
  ElMessageBox.confirm(
    `确定要删除该优惠券吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    await couponApi.deleteCoupon(row.id)
    ElMessage.success('删除成功')
    getCouponList()
  }).catch(() => {
    // 取消操作
  })
}

// 查看兑换码
const handleViewCodes = (row: CouponListResponseType) => {
  // 这里应该跳转到查看兑换码的页面或者弹出一个模态框展示兑换码
}

// 初始化加载数据
onMounted(() => {
  getCouponList()
})

// 辅助函数
const getDiscountTypeName = (type: number) => {
  switch (type) {
    case 1: return '每满减';
    case 2: return '折扣';
    case 3: return '无门槛';
    case 4: return '满减';
    default: return '';
  }
}

const getObtainWayName = (way: number) => {
  return way === 1 ? '手动领取' : '兑换码';
}

const getStatusName = (status: number) => {
  switch (status) {
    case 1: return '待发放';
    case 2: return '未开始';
    case 3: return '进行中';
    case 4: return '已结束';
    case 5: return '暂停';
    default: return '';
  }
}

const getStatusType = (status: number) => {
  switch (status) {
    case 1: return 'info';
    case 2: return 'primary';
    case 3: return 'success';
    case 4: return 'warning';
    case 5: return 'danger';
    default: return '';
  }
}

</script>

<style scoped>
.coupon-list {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}
</style>